package slh.commentVote;


import slh.ConSql;

import java.sql.*;

public class commentVoteDao {
    public boolean addVote(int commentId, String userId, int voteType) throws SQLException {
        String sql = "INSERT INTO comment_votes (comment_id, user_id, vote_type) VALUES (?, ?, ?) " +
                "ON DUPLICATE KEY UPDATE vote_type = VALUES(vote_type)";

        try (Connection conn = ConSql.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, commentId);
            stmt.setString(2, userId);
            stmt.setInt(3, voteType);
            return stmt.executeUpdate() > 0;
        }
    }

    public boolean removeVote(int commentId, String userId) throws SQLException {
        String sql = "DELETE FROM comment_votes WHERE comment_id = ? AND user_id = ?";

        try (Connection conn = ConSql.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, commentId);
            stmt.setString(2, userId);
            return stmt.executeUpdate() > 0;
        }
    }

    public Integer getUserVote(int commentId, String userId) throws SQLException {
        String sql = "SELECT vote_type FROM comment_votes WHERE comment_id = ? AND user_id = ?";

        try (Connection conn = ConSql.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, commentId);
            stmt.setString(2, userId);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    return rs.getInt("vote_type");
                }
                return null;
            }
        }
    }

    public int[] getVoteCounts(int commentId) throws SQLException {
        String sql = "SELECT " +
                "SUM(CASE WHEN vote_type = 1 THEN 1 ELSE 0 END) as up_votes, " +
                "SUM(CASE WHEN vote_type = -1 THEN 1 ELSE 0 END) as down_votes " +
                "FROM comment_votes WHERE comment_id = ?";

        try (Connection conn = ConSql.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, commentId);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    return new int[]{rs.getInt("up_votes"), rs.getInt("down_votes")};
                }
                return new int[]{0, 0};
            }
        }
    }
}
